from django.contrib.admin.templatetags.admin_list import pagination
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse, get_object_or_404
from pyexpat.errors import messages

from main.models import Files, Comment
from .forms import RegistForm, LoginForm, ChangeForm, FilesForm, CommentForm
from .models import CustomUser
from django.contrib.auth import login as lgi, logout as lgo
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash

from django.views.generic import ListView
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView

import smtplib


# Create your views here.

# def login_required(f):
#     def check(request):
#         if request.user.is_authenticated:
#             return  f()
#         else:
#             return redirect(reverse('user:login'))
#
#     return check


def home(request):
    return render(request, 'user/home.html')


@login_required
def change(request):
    if request.method == 'POST':
        cf = ChangeForm(request.POST)
        if cf.is_valid():
            if request.user.check_password(cf.cleaned_data['oldpassword']):
                request.user.set_password(cf.cleaned_data['password'])
                request.user.save()
                logout(request)
                return redirect(reverse('user:login'))
            else:
                cf.add_error("oldpassword", "原始密码不正确")
                return render(request, 'user/change.html', context={'form': cf})
        else:
            return render(request, 'user/change.html', context={'form': cf})
    else:
        cf = ChangeForm()
        return render(request, 'user/change.html', context={'form': cf})


def logout(request):
    lgo(request)
    return redirect(reverse('user:login'))


@login_required
def center(request):
    print("+++++++")
    if request.user.is_authenticated:
        return render(request, 'user/center.html')
    else:
        return redirect(reverse('user:login'))


def login(request):
    if request.method == 'POST':
        lf = LoginForm(request.POST)
        if lf.is_valid():
            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first() or CustomUser.objects.filter(
                email=lf.cleaned_data['email']).first()
            if user:
                if user.check_password(lf.cleaned_data['password']):
                    if user.is_active:
                        lgi(request, user)
                        return redirect(reverse('main:index'))
                    else:
                        lf.add_error("username", "该账户尚未激活")
                        return render(request, 'user/login.html', {'form': lf})
                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {'form': lf})
            else:
                lf.add_error("username", "用户名不存在")
                return render(request, 'user/login.html', {'form': lf})
        else:
            return render(request, 'user/login.html', {'form': lf})

    else:
        lf = LoginForm()
        return render(request, 'user/login.html', {'form': lf})


def regist(request):
    if request.method == 'POST':
        rf = RegistForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.is_active = False
            user.username = user.email
            user.set_password(rf.cleaned_data['password'])
            user.save()

            user.email_user("激活账户", message="",
                            html_message=f"<a href='http://127.0.0.1:8000/user/active/{user.id}'>点我激活</a>")
            print(f"注册用户{user}成功,id:{user.id}")

            return redirect(reverse('user:login'))
        else:
            return render(request, 'user/regist.html', context={'form': rf})
    else:
        rf = RegistForm()
        return render(request, 'user/regist.html', context={'form': rf})


def active(request, id):
    user = CustomUser.objects.filter(id=id).first()
    if user:
        user.is_active = True
        user.save()
        return redirect(reverse('user:login'))
    else:
        return HttpResponse("激活失败")


class FilesCreateView(CreateView):
    model = Files
    form_class = FilesForm
    template_name = 'user/files_form.html'

    # success_url = reverse_lazy('user:article_list')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class FilesListView(ListView):
    # model = Article
    template_name = 'user/files_list.html'
    def get_queryset(self):
        qs = Files.objects.filter(author=self.request.user)  # 原来功能：只拿自己的
        # 非管理员再额外屏蔽未通过
        if not self.request.user.is_superuser:
            qs = qs.filter(state='success')
        return qs.order_by('-create_time')



class FilesUpdateView(UpdateView):
    template_name = 'user/files_form.html'
    model = Files
    form_class = FilesForm

    def get_context_data(self, **kwargs):
        """传递返回地址到模板"""
        context = super().get_context_data(**kwargs)
        # 获取返回地址
        back = self.request.GET.get('back') or self.request.META.get('HTTP_REFERER', '')
        context['back_url'] = back
        return context

    def form_valid(self, form):
        # 保存表单数据
        self.object = form.save()

        # 获取返回地址
        back = self.request.POST.get('back') or self.request.GET.get('back')

        # 返回原来的页面
        if back:
            return redirect(back)
        else:
            # 如果没有返回地址，默认跳转到文件详情页
            return redirect('main:index')



class FilesDeleteView(DeleteView):
    template_name = 'user/files_confirm_delete.html'
    model = Files
    success_url = reverse_lazy('main:index')


    def form_valid(self, form):
        # 1. 先拿到回来地址
        back = self.request.POST.get('back') or self.request.GET.get('back')
        # 2. 再删除对象
        self.object.delete()
        # 3. 返回列表页（或兜底首页）
        if back:
            return redirect(back)
        return redirect('main:index')

def ManagefilesView(request,):
    f = Files.objects.filter(author=request.user).order_by('-create_time')

    context = {
        'files': f
    }
    return render(request, 'user/manage_files.html',context)

